<template>
  <div class="notice__scroll mt10 fs12">
    <div class="notice__list_wrapper">
      <div class="notice__list" :class="{ moving: moving }" ref="refNoticeList">
        <div class="notice__item" v-for="item in list" :key="item">{{ item }}</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: '',
  props: {
    products: {
      default: () => ([]),
      type: Array
    }
  },
  data: () => ({
    list: [],
    moving: false
  }),
  methods: {
    randomPhone () {
      const start = ['134', '135', '136', '137', '138', '139', '147', '150', '151', '152', '157', '158', '159', '178', '182', '183', '184', '187', '188', '198']
      const end = '1234567890'
      const prefix = start[Math.floor(Math.random() * start.length)]
      let suffix = ''
      for (let i = 0; i < 4; i++) {
        suffix += end.charAt(Math.floor(Math.random() * end.length))
      }
      return prefix + '****' + suffix
    },
    randomProduct () {
      const len = this.products.length
      const index = Math.floor(Math.random() * len)
      return this.products[index]?.name || '1年'
    },
    randomItem (len = 2) {
      const list = []
      for (let i = 0; i < len; i++) {
        list.push(`${this.randomPhone()}刚购买了${this.randomProduct()}会员`)
      }
      return list
    },
    startAnimation () {
      this.moving = false
      this.timer = setTimeout(() => {
        this.moving = true
      }, 3000)
    },
    handleTransition () {
      this.list[0] = this.list[1]
      this.list[1] = this.randomItem(1)[0]
      this.$nextTick(() => {
        this.startAnimation()
      })
    },
    initListener () {
      this.$_transitionHandler = () => {
        this.handleTransition()
      }
      this.$refs.refNoticeList.addEventListener('transitionend', this.$_transitionHandler)
    },
    destroyListener () {
      this.$refs.refNoticeList && this.$refs.refNoticeList.removeEventListener('transitionend', this.$_transitionHandler)
      clearTimeout(this.timer)
      this.$_transitionHandler = null
    }
  },
  mounted () {
    this.list = this.randomItem(2)
    this.initListener()
    this.startAnimation()
  },
  activated () {
    if (!this.$_transitionHandler) {
      this.initListener()
    }
    this.startAnimation()
  },
  deactivated () {
    this.destroyListener()
  },
  destroyed () {
    this.destroyListener()
  }
}
</script>

<style lang="scss" scoped>
.notice__scroll {
  display: inline-block;
  background: rgba(#F8DE9D, 0.1);
  border-radius: 4px;
  padding: 4px 10px;
  font-size: 12px;
  color: #F8DE9D;
  min-width: 268px;
  text-align: center;
}
.notice__list_wrapper {
  height: 16px;
  line-height: 16px;
  overflow: hidden;

}
.notice__list {
  &.moving {
    transition: transform 0.5s linear;
    transform: translateY(-16px);
  }
}

.notice__item {
  border-radius: 4px;
}
</style>
